import axios from 'axios';

// process.env.NODE_ENV === 'development' 来判断是否开发环境

var API_BASEURL = "http://localhost:5050"
//baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
axios.defaults.baseURL = API_BASEURL;
axios.defaults.withCredentials = true;
axios.defaults.timeout = 5000;

async function ajax(url = '', params = {}, type = 'GET') {

    try {        
        type = type.toUpperCase();
        if (type === 'GET') {
            // 拼接字符串
            let paramsStr = '';
            // 遍历
            Object.keys(params).forEach(key => {
                paramsStr += key + '=' + params[key] + '&';
            });
            // 过滤最后的&
            if (paramsStr) {
                paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'));
                url += '?' + paramsStr;
            }
            // 发起get请求
            return await axios.get(url);
        } else if (type.toUpperCase() === 'POST') {
            // 发起post请求
            return await axios.post(url, params);
        } else {
            throw `目前前端封装API不支持${type}请求`;
        }         
    } catch (error) {
        return { code: -1, msg: '异步调用出错了，错误信息:' + error };
    }
}

axios.interceptors.request.use(
    config => {
        //     // 在发送请求之前做些什么
        // Indicator.open({
        //     text: 'Loading...',
        //     spinnerType: 'fading-circle'
        // });
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

export default ajax;
